package com.sgb.kjwl.view.ui.activity.self.driver;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.UploadTransportQCertificateActivityBinding;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.ImageUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.self.CameraActivity;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.sgb.kjwl.viewmodel.self.driver.UploadTransportCertificateModel;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.List;

import static com.sgb.link.router.PathDriver.UploadTransportQualificationCertificateActivity;

/**
 * Describe:    上传道路运输从业资格证（自营司机）
 * Author:  yangLei
 * Date:    2021/10/15
 */
@Route(path = UploadTransportQualificationCertificateActivity)
public class UploadTransportQualificationCertificateActivity extends BaseActivity<UploadTransportCertificateModel, UploadTransportQCertificateActivityBinding> {
    @Autowired(name = RouterKey.NO, desc = "司机的no")
    public String userNo;
    private ChoosePictureDialog mChoosePictureDialog;//选择照片
    /**
     * 照片类型
     */
    private int type;
    public final int CERTIFICATE_MAIN = 1;   //驾驶照正页
    public final int CERTIFICATE_DEPUTY = 2;  //驾驶证副页

    private String homePageUrl;
    private String sidelineUrl;

    @Override
    protected int layoutId() {
        return R.layout.upload_transport_q_certificate_activity;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(UploadTransportCertificateModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(userNo)) {
            showToast("司机no为空");
            finish();
        }

        initViews();
        initEvents();
    }

    private void initViews() {
        mBinding.includeTitle.titleView.setText("上传证件");
    }

    private void initEvents() {
        mBinding.setOnClick(this::onClick);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mViewModel.submitLD.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {
                showToast("操作成功");
                setResult(200);
                finish();
            }
        });
    }

    /**
     * 上传图片成功
     *
     * @param url
     * @param type
     */
    public void uploadImgSuccess(String url, int type) {
        if (type == CERTIFICATE_MAIN) {
            homePageUrl = url;
        } else if (type == CERTIFICATE_DEPUTY) {
            sidelineUrl = url;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_certificates:
                mChoosePictureDialog = new ChoosePictureDialog(this, R.drawable.img_cy_mian);
                mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                    @Override
                    public void onItemClick(String ids) {
                        if (ids.equals("拍照")) {
                            startCamera(CERTIFICATE_MAIN);
                        } else if (ids.equals("从手机相册选择")) {
                            getImageByAlbum(CERTIFICATE_MAIN);
                        }
                    }
                });
                mChoosePictureDialog.show(getSupportFragmentManager(), "1");
                break;

            case R.id.img_del1:
                homePageUrl = "";
                mBinding.ivCertificates.setImageDrawable(getResources().getDrawable(R.drawable.img_cy_zhengmian));
                mBinding.imgDel1.setVisibility(View.GONE);
                break;

            case R.id.iv_certificates_2:
                mChoosePictureDialog = new ChoosePictureDialog(this, R.drawable.img_cy_second_page);
                mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                    @Override
                    public void onItemClick(String ids) {
                        if (ids.equals("拍照")) {
                            startCamera(CERTIFICATE_DEPUTY);
                        } else if (ids.equals("从手机相册选择")) {
                            getImageByAlbum(CERTIFICATE_DEPUTY);
                        }
                    }
                });
                mChoosePictureDialog.show(getSupportFragmentManager(), "2");
                break;

            case R.id.img_del2:
                sidelineUrl = "";
                mBinding.ivCertificates.setImageDrawable(getResources().getDrawable(R.drawable.img_cy_second_page));
                mBinding.imgDel2.setVisibility(View.GONE);
                break;

            case R.id.submit:
                if (TextUtils.isEmpty(homePageUrl)) {
                    showToast("请上传从业资格证主页");
                    return;
                }
                if (TextUtils.isEmpty(sidelineUrl)) {
                    showToast("请上传从业资格证副页");
                    return;
                }
                mViewModel.uploadCertificate(this, homePageUrl, sidelineUrl, userNo);
                break;

        }
    }

    public void showToast(String text) {
        MToast.showToast(getApplicationContext(), text);
    }

    /**
     * 调用相机拍照
     *
     * @param type
     */
    private void startCamera(int type) {
        this.type = type;
        if (this.type == CERTIFICATE_MAIN) {
            CameraActivity.start(this, 1, "从业资格证主页", PictureConfig.REQUEST_CAMERA);
        } else {
            CameraActivity.start(this, 1, "从业资格证副页", PictureConfig.REQUEST_CAMERA);
        }
    }

    /**
     * 从相册获取图片
     *
     * @param type
     */
    private void getImageByAlbum(int type) {
        this.type = type;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .compress(true)//是否压缩
                .minimumCompressSize(2 * 1024)//小于2M不压缩
                .maxSelectNum(1)//能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    File file = new File(selectList.get(0).getRealPath());
                    MLog.d("图片路径：", selectList.get(0).getRealPath());
                    if (file.exists()) {
                        MLog.d("图片", "存在");
                    }
                    if (CERTIFICATE_MAIN == type) {
                        Glide.with(this).load(file).into(mBinding.ivCertificates);
                        mBinding.imgDel1.setVisibility(View.GONE);
                        mViewModel.uploadMutFileModel(this, ImageUtil.getImage(selectList.get(0).getRealPath()), CERTIFICATE_MAIN);
                    } else if (type == CERTIFICATE_DEPUTY) {
                        //Bugly报file为空
                        if (file.length() > 0) {
                            Glide.with(this).load(file).into(mBinding.ivCertificates2);
                            mBinding.imgDel2.setVisibility(View.GONE);
                        }
                        if (!TextUtils.isEmpty(selectList.get(0).getRealPath())) {
                            mViewModel.uploadMutFileModel(this, ImageUtil.getImage(selectList.get(0).getRealPath()), CERTIFICATE_DEPUTY);
                        }
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    String path = data.getStringExtra("imagePath");
                    File takePictureFile = new File(path);
                    if (CERTIFICATE_MAIN == type) {
                        Glide.with(this).load(takePictureFile).into(mBinding.ivCertificates);
                        mViewModel.uploadMutFileModel(this, ImageUtil.getImage(path), CERTIFICATE_MAIN);
                    } else if (type == CERTIFICATE_DEPUTY) {
                        //Bugly报file为空
                        if (takePictureFile.length() > 0) {
                            Glide.with(this).load(takePictureFile).into(mBinding.ivCertificates2);
                        }
                        if (!TextUtils.isEmpty(path)) {
                            mViewModel.uploadMutFileModel(this, ImageUtil.getImage(path), CERTIFICATE_DEPUTY);
                        }
                    }
            }
        }
    }
}
